package com.hnjz.common.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.i18n.LocaleContextHolder;

/**
 * Date Utility Class
 * This is used to convert Strings to Dates and Timestamps
 *
 * <p>
 * <a href="DateDifferenceUtil.java.html"><i>View Source</i></a>
 * </p>
 * 
 * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
 *  Modified by <a href="mailto:dan@getrolling.com">Dan Kibler </a> 
 *   to correct time pattern. Minutes should be mm not MM
 * 	(MM is month). 
 * @version $Revision: 1.1 $ $Date: 2007/09/25 03:11:15 $
 */
public class DateUtil {

    private static Log    log                = LogFactory.getLog(DateUtil.class);
    private static String defaultDatePattern = null;
    private static String timePattern        = "HH:mm";

    //用来全局控制 上一周，本周，下一周的周数变化
    private int           weeks              = 0;
    private int           MaxDate;                                               //一月最大天数
    private int           MaxYear;                                               //一年最大天数

    /**
     * Return default datePattern (yyyy-MM-dd)
     * @return a string representing the date pattern on the UI
     */
    public static synchronized String getDatePattern() {
        Locale locale = LocaleContextHolder.getLocale();
        try {
            defaultDatePattern = ResourceBundle.getBundle("yyyy-MM-dd", locale).getString(
                "date.format");
        } catch (MissingResourceException mse) {
            defaultDatePattern = "yyyy-MM-dd";
        }

        return defaultDatePattern;
    }

    /**
     * Return default datePattern (yyyy-MM-dd)
     * @return a string representing the date pattern on the UI
     */
    public static synchronized String getDatePatternMin() {
        Locale locale = LocaleContextHolder.getLocale();
        try {
            defaultDatePattern = ResourceBundle.getBundle("yyyy-MM-dd HH:mm", locale).getString(
                "date.format");
        } catch (MissingResourceException mse) {
            defaultDatePattern = "yyyy-MM-dd HH:mm";
        }

        return defaultDatePattern;
    }

    /**
     * This method attempts to convert an Oracle-formatted date
     * in the form dd-MMM-yyyy to yyyy-MM-dd.
     *
     * @param aDate date from database as a string
     * @return formatted string for the ui
     */
    public static final String getDate(Date aDate) {
        SimpleDateFormat df = null;
        String returnValue = "";

        if (aDate != null) {
            df = new SimpleDateFormat(getDatePattern());
            returnValue = df.format(aDate);
        }

        return (returnValue);
    }

    public static final String getYear(Date aDate) {
        SimpleDateFormat df = null;
        String year = "";

        if (aDate != null) {
            df = new SimpleDateFormat(getDatePattern());
            year = df.format(aDate);
        }
        year = year.substring(0, 4);
        return (year);
    }

    public static final String getQuarter(Date aDate) {
        SimpleDateFormat df = null;
        String quarter = "";

        if (aDate != null) {
            df = new SimpleDateFormat(getDatePattern());
            String time = df.format(aDate);
            String[] times = time.split("-");
            String month = times[1];
            if ("1".equals(month) || "2".equals(month) || "3".equals(month)) {
                quarter = "1";
            }
            if ("4".equals(month) || "5".equals(month) || "6".equals(month)) {
                quarter = "2";
            }
            if ("7".equals(month) || "8".equals(month) || "9".equals(month)) {
                quarter = "3";
            }
            if ("10".equals(month) || "11".equals(month) || "12".equals(month)) {
                quarter = "4";
            }
        }

        return (quarter);
    }

    public static final int[] getMonths(String quarter) {
        int[] months = new int[3];
        if (null != quarter && !"".equals(quarter)) {
            if ("1".equals(quarter)) {
                months[0] = 1;
                months[1] = 2;
                months[2] = 3;
            }
            if ("2".equals(quarter)) {
                months[0] = 4;
                months[1] = 5;
                months[2] = 6;
            }
            if ("3".equals(quarter)) {
                months[0] = 7;
                months[1] = 8;
                months[2] = 9;
            }
            if ("4".equals(quarter)) {
                months[0] = 10;
                months[1] = 11;
                months[2] = 12;
            }
        }
        return months;
    }

    /**
     * This method generates a string representation of a date/time
     * in the format you specify on input
     *
     * @param aMask the date pattern the string is in
     * @param strDate a string representation of a date
     * @return a converted Date object
     * @see java.text.SimpleDateFormat
     * @throws ParseException
     */
    public static final Date convertStringToDate(String aMask, String strDate)
                                                                              throws ParseException {
        Date date = null;
        SimpleDateFormat df = new SimpleDateFormat(aMask);
        try {
            date = df.parse(strDate);
        } catch (ParseException pe) {
            //log.error("ParseException: " + pe);
            throw new ParseException(pe.getMessage(), pe.getErrorOffset());
        }

        return (date);
    }

    /**
     * This method returns the current date time in the format:
     * MM/dd/yyyy HH:MM a
     *
     * @param theTime the current time
     * @return the current date/time
     */
    public static String getTimeNow(Date theTime) {
        return getDateTime(timePattern, theTime);
    }

    public static Date getStartDatetime(String date) {
        SimpleDateFormat ddf = new SimpleDateFormat("yyyy-MM-dd");
        Date d = null;
        try {
            d = ddf.parse(date);
        } catch (Exception e) {
        }
        String nd = "";
        if (null != d) {
            nd = ddf.format(d) + " 00:00:00";
        }
        SimpleDateFormat tdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date cd = null;
        if (!"".equals(nd)) {
            try {
                cd = tdf.parse(nd);
            } catch (Exception e) {
            }
        }
        return cd;
    }

    public static Date getEndDatetime(String date) {
        SimpleDateFormat ddf = new SimpleDateFormat("yyyy-MM-dd");
        Date d = null;
        try {
            d = ddf.parse(date);
        } catch (Exception e) {
        }
        String nd = "";
        if (null != d) {
            nd = ddf.format(d) + " 23:59:59";
        }
        SimpleDateFormat tdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date cd = null;
        if (!"".equals(nd)) {
            try {
                cd = tdf.parse(nd);
            } catch (Exception e) {
            }
        }
        return cd;
    }

    /**
     * This method returns the current date in the format: yyyy-MM-dd
     * 
     * @return the current date
     * @throws ParseException
     */
    public static Calendar getToday() throws ParseException {
        Date today = new Date();
        SimpleDateFormat df = new SimpleDateFormat(getDatePattern());

        // This seems like quite a hack (date -> string -> date),
        // but it works ;-)
        String todayAsString = df.format(today);
        Calendar cal = new GregorianCalendar();
        cal.setTime(convertStringToDate(todayAsString));

        return cal;
    }

    /**
     * This method generates a string representation of a date's date/time
     * in the format you specify on input
     *
     * @param aMask the date pattern the string is in
     * @param aDate a date object
     * @return a formatted string representation of the date
     * 
     * @see java.text.SimpleDateFormat
     */
    public static final String getDateTime(String aMask, Date aDate) {
        SimpleDateFormat df = null;
        String returnValue = "";

        if (aDate == null) {
            log.error("aDate is null!");
        } else {
            df = new SimpleDateFormat(aMask);
            returnValue = df.format(aDate);
        }

        return (returnValue);
    }

    /**
     * 同getDateTime(String aMask, Date aDate) ,只是把参数顺序改了一下
     * @param aDate
     * @param aMask
     * @return
     */
    public static final String getDateTime(Date aDate, String aMask) {
        return getDateTime(aMask, aDate);
    }

    public static final String getDateTime(Date aDate) {
        return getDateTime("yyyy-MM-dd HH:mm:ss", aDate);
    }

    public static final String getForDateTime(Date aDate) {
        return getDateTime("yyyy-MM-dd", aDate);
    }

    /**
     * This method generates a string representation of a date based
     * on the System Property 'dateFormat'
     * in the format you specify on input
     * 
     * @param aDate A date to convert
     * @return a string representation of the date
     */
    public static final String convertDateToString(Date aDate) {
        return getDateTime(getDatePattern(), aDate);
    }

    /**
     * This method generates a string representation of a date based
     * on the System Property 'dateFormat'
     * in the format you specify on input
     * 
     * @param aDate A date to convert
     * @return a string representation of the date
     */
    public static final String convertDateToStringMin(Date aDate) {
        return getDateTime(getDatePatternMin(), aDate);
    }

    /**
     * This method converts a String to a date using the datePattern
     * 
     * @param strDate the date to convert (in format yyyy-MM-dd)
     * @return a date object
     * 
     * @throws ParseException
     */
    public static Date convertStringToDate(String strDate) throws ParseException {
        Date aDate = null;

        try {
            aDate = convertStringToDate(getDatePattern(), strDate);
        } catch (ParseException pe) {
            log.error("Could not convert '" + strDate + "' to a date, throwing exception");
        }

        return aDate;
    }

    /**
     * 函数描述：得到时间区间的差集
     * 
     * @return
     */
    public static List<Date[]> getDifference(Date kDate, Date jDate, Date delkDate, Date deljDate) {
        List<Date[]> listDate = new ArrayList<Date[]>();
        Date[] date;
        //当要删除的开始时间大于原开始时间时
        if (compareDate(delkDate, kDate) == 1) {
            date = new Date[] { kDate, DateUtil.getZero(delkDate, -1) };
            listDate.add(date);
        }
        //当要删除的结束时间小于原结束时间时
        if (compareDate(deljDate, jDate) == -1) {
            date = new Date[] { jDate, DateUtil.getZero(deljDate, 1) };
            listDate.add(date);
        }

        return listDate;
    }

    /**
     * 函数描述：排序
     * 
     * @return
     */
    public static Date[][] getTaxis(Date[][] dates, boolean desc) {
        int x = 1;
        if (desc) {
            x = -1;
        }
        // 对dates排序
        for (int i = 0; i < dates.length; i++) {
            int k = i;
            for (int j = i + 1; j < dates.length; j++) {
                if (compareDate(dates[k][1], dates[j][1]) == x) {
                    k = j;
                }
            }
            if (k != i) {
                Date tempk = dates[k][0];
                Date tempj = dates[k][1];
                dates[k][0] = dates[i][0];
                dates[k][1] = dates[i][1];
                dates[i][0] = tempk;
                dates[i][1] = tempj;
            }

        }
        return dates;
    }

    /**
     * 函数描述：得到时间区间的天数
     * 
     * @return
     */
    public static int getDays(Date kDate, Date jDate) {
        return (int) ((jDate.getTime() - kDate.getTime()) / (1000 * 60 * 60 * 24));
    }

    /**
     * 函数描述：得到时间区间数组的交集
     * 
     * @return 返回时间区间交集，没前交集返回null
     */
    public static Date[] getIntersection(Date kDate, Date jDate, Date kDate2, Date jDate2) {
        if (kDate.after(jDate2))//开始时间1在结束时间2之后，那么没有交集
            return null;
        if (jDate.before(kDate2))//结束时间1在开始时间2之后，那么没有交集
            return null;

        if (kDate.after(kDate2))//如果开始时间1在开始时间2之后，
        {
            if (jDate.before(jDate2))//检查结束时间1同结束结束时间2比较的结果
            {
                return getIntersection(kDate, jDate);
            } else {
                return getIntersection(kDate, jDate2);
            }
        } else {
            if (jDate.before(jDate2))//检查结束时间1同结束结束时间2比较的结果
            {
                return getIntersection(kDate2, jDate);
            } else {
                return getIntersection(kDate2, jDate2);
            }

        }
    }

    /**
     * 函数描述：得到时间区间数组的交集
     * 
     * @return
     */
    private static Date[] getIntersection(Date start, Date end) {
        Date result[] = new Date[2];
        result[0] = start;
        result[1] = end;
        return result;
    }

    /**
     * 函数描述：得到时间区间数组的差集
     * 
     * @return
     */
    public static Date[][] getDifferences(Date[][] dates, Date[][] delDates) {
        List<Date[]> listDate = new ArrayList<Date[]>();
        Date[][] outDate;
        delDates = getTaxis(delDates, false);// 对delDates排序

        for (int j = 0; j < dates.length; j++) {
            for (int i = 0; i < delDates.length; i++) {

                // 当要删除的区间和原区间有交集的时候
                if ((compareDate(delDates[i][1], dates[j][0]) >= 0 && compareDate(delDates[i][1],
                    dates[j][1]) <= 0)
                    || (compareDate(delDates[i][0], dates[j][0]) >= 0 && compareDate(
                        delDates[i][0], dates[j][1]) <= 0)) {
                    listDate.addAll(getDifference(dates[i][0], dates[i][1], delDates[i][0],
                        delDates[i][1]));

                }
                //当原时间的结束时间小于删除时间的结束时间时
                if (compareDate(dates[j][1], delDates[i][1]) <= 0) {
                    break;
                }
            }
        }
        outDate = new Date[listDate.size()][2];
        int n = 0;
        for (Date[] date : listDate) {
            outDate[n][0] = date[0];
            outDate[n][1] = date[1];
            n++;
        }
        return outDate;
    }

    /**
     * 
     *函数描述：比较日期
     * @param date1  日期1
     * @param date2  日期2
     * @return  当date1大时返回 1 当相等时返回0  其他为-1
     */
    public static int compareDate(Date date1, Date date2) {
        if (date1 == null && date2 != null) {
            return -1;
        } else if (date1 != null && date2 == null) {
            return 1;
        } else if (date1 == null && date2 == null) {
            return 0;
        }
        int outInt = 0;
        if (date1.after(date2)) {
            outInt = 1;
        }
        if (date1.before(date2)) {
            outInt = -1;
        }
        return outInt;
    }

    /**
     * 函数描述：将给定日期的时分秒清零
     * @param date	指定的日期
     * @return
     */
    public static Date getZero(Date date) {
        return getZero(date, 0);
    }

    /**
     * 	 *函数描述：将给定日期增减（N）天后的时分秒清零
     * @param date 指定日期
     * @param days	增减的天数
     * @return
     */
    public static Date getZero(Date date, int days) {
        if (date == null) {
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, days);//天数+n
        calendar.set(Calendar.HOUR_OF_DAY, 0);//小时置0
        calendar.set(Calendar.MINUTE, 0);//分钟置0
        calendar.set(Calendar.SECOND, 0);//秒置0
        calendar.set(Calendar.MILLISECOND, 0);//毫秒置0
        Date newDate = calendar.getTime();//得到新的date对象.
        return newDate;
    }

    /**
     * 	 *函数描述：将给定日期增减（N）天后的时分秒清零
     * @param date 指定日期
     * @param days	增减的天数
     * @return
     */
    public static Date getZero(Date date, int years, int months, int days) {
        if (date == null) {
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, years);//年数+n
        calendar.add(Calendar.MONTH, months);//月数+n
        calendar.add(Calendar.DATE, days);//天数+n
        calendar.set(Calendar.HOUR_OF_DAY, 0);//小时置0
        calendar.set(Calendar.MINUTE, 0);//分钟置0
        calendar.set(Calendar.SECOND, 0);//秒置0
        calendar.set(Calendar.MILLISECOND, 0);//毫秒置0
        Date newDate = calendar.getTime();//得到新的date对象.
        return newDate;
    }

    /**
     *  函数描述：根据年和月，返回这个月的最后一天的数字。
     * @param year
     * @param month
     * @return
     */
    public static int getLastDayOfMoney(int year, int month) {
        int lastDay = 30;
        if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10
            || month == 12) {
            lastDay = 31;
        } else if (month == 2) {
            lastDay = 28;
            if (year % 4 == 0) {
                lastDay = 29;
                if (year % 100 == 0) {
                    if (year % 400 != 0) {
                        lastDay = 28;
                    }
                }
            }
        }
        return lastDay;
    }

    //获得本年第一天的日期   
    public String getCurrentYearFirst() {
        int yearPlus = this.getYearPlus();
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add(GregorianCalendar.DATE, yearPlus);
        Date yearDay = currentDate.getTime();
        DateFormat df = DateFormat.getDateInstance();
        String preYearDay = df.format(yearDay);
        return preYearDay;
    }

    //获得本年最后一天的日期 *   
    public String getCurrentYearEnd() {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");//可以方便地修改日期格式      
        String years = dateFormat.format(date);
        return years + "-12-31";
    }

    //获得上年第一天的日期 *   
    public String getPreviousYearFirst() {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");//可以方便地修改日期格式      
        String years = dateFormat.format(date);
        int years_value = Integer.parseInt(years);
        years_value--;
        return years_value + "-1-1";
    }

    //获得上年最后一天的日期   
    public String getPreviousYearEnd() {
        weeks--;
        int yearPlus = this.getYearPlus();
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add(GregorianCalendar.DATE, yearPlus + MaxYear * weeks + (MaxYear - 1));
        Date yearDay = currentDate.getTime();
        DateFormat df = DateFormat.getDateInstance();
        String preYearDay = df.format(yearDay);
        getThisSeasonTime(11);
        return preYearDay;
    }

    //获得本季度   
    public String getThisSeasonTime(int month) {
        int array[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 10, 11, 12 } };
        int season = 1;
        if (month >= 1 && month <= 3) {
            season = 1;
        }
        if (month >= 4 && month <= 6) {
            season = 2;
        }
        if (month >= 7 && month <= 9) {
            season = 3;
        }
        if (month >= 10 && month <= 12) {
            season = 4;
        }
        int start_month = array[season - 1][0];
        int end_month = array[season - 1][2];

        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");//可以方便地修改日期格式      
        String years = dateFormat.format(date);
        int years_value = Integer.parseInt(years);

        int start_days = 1;//years+"-"+String.valueOf(start_month)+"-1";//getLastDayOfMonth(years_value,start_month);   
        int end_days = getLastDayOfMonth(years_value, end_month);
        String seasonDate = years_value + "-" + start_month + "-" + start_days + ";" + years_value
                            + "-" + end_month + "-" + end_days;
        return seasonDate;

    }

    /** 
     * 获取某年某月的最后一天 
     * @param year 年 
     * @param month 月 
     * @return 最后一天 
     */
    private int getLastDayOfMonth(int year, int month) {
        if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10
            || month == 12) {
            return 31;
        }
        if (month == 4 || month == 6 || month == 9 || month == 11) {
            return 30;
        }
        if (month == 2) {
            if (isLeapYear(year)) {
                return 29;
            } else {
                return 28;
            }
        }
        return 0;
    }

    /** 
     * 是否闰年 
     * @param year 年 
     * @return   
     */
    public boolean isLeapYear(int year) {
        return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
    }

    /**
         * 得到二个日期间的间隔天数
         */
    public static String getTwoDay(String sj1, String sj2) {
        SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
        long day = 0;
        try {
            java.util.Date date = myFormatter.parse(sj1);
            java.util.Date mydate = myFormatter.parse(sj2);
            day = (date.getTime() - mydate.getTime()) / (24 * 60 * 60 * 1000);
        } catch (Exception e) {
            return "";
        }
        return day + "";
    }

    /**
         * 根据一个日期，返回是星期几的字符串
         * 
         * @param sdate
         * @return
         */
    public static String getWeek(String sdate) {
        // 再转换为时间
        Date date = DateUtil.strToDate(sdate);
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        // int hour=c.get(Calendar.DAY_OF_WEEK);
        // hour中存的就是星期几了，其范围 1~7
        // 1=星期日 7=星期六，其他类推
        return new SimpleDateFormat("EEEE").format(c.getTime());
    }

    /**
         * 将短时间格式字符串转换为时间 yyyy-MM-dd 
         * 
         * @param strDate
         * @return
         */
    public static Date strToDate(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return strtodate;
    }

    /**
         * 两个时间之间的天数
         * 
         * @param date1
         * @param date2
         * @return
         */
    public static long getDays(String date1, String date2) {
        if (date1 == null || date1.equals(""))
            return 0;
        if (date2 == null || date2.equals(""))
            return 0;
        // 转换为标准时间
        SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
        java.util.Date date = null;
        java.util.Date mydate = null;
        try {
            date = myFormatter.parse(date1);
            mydate = myFormatter.parse(date2);
        } catch (Exception e) {
        }
        long day = (date.getTime() - mydate.getTime()) / (24 * 60 * 60 * 1000);
        return day;
    }

    // 计算当月最后一天,返回字符串
    public String getDefaultDay() {
        String str = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Calendar lastDate = Calendar.getInstance();
        lastDate.set(Calendar.DATE, 1);//设为当前月的1号
        lastDate.add(Calendar.MONTH, 1);//加一个月，变为下月的1号
        lastDate.add(Calendar.DATE, -1);//减去一天，变为当月最后一天

        str = sdf.format(lastDate.getTime());
        return str;
    }

    // 上月第一天
    public String getPreviousMonthFirst() {
        String str = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Calendar lastDate = Calendar.getInstance();
        lastDate.set(Calendar.DATE, 1);//设为当前月的1号
        lastDate.add(Calendar.MONTH, -1);//减一个月，变为下月的1号
        //lastDate.add(Calendar.DATE,-1);//减去一天，变为当月最后一天

        str = sdf.format(lastDate.getTime());
        return str;
    }

    //获取当月第一天
    public String getFirstDayOfMonth() {
        String str = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Calendar lastDate = Calendar.getInstance();
        lastDate.set(Calendar.DATE, 1);//设为当前月的1号
        str = sdf.format(lastDate.getTime());
        return str;
    }

    // 获得本周星期日的日期 
    public String getCurrentWeekday() {
        weeks = 0;
        int mondayPlus = getMondayPlus();
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add(GregorianCalendar.DATE, mondayPlus + 6);
        Date monday = currentDate.getTime();

        DateFormat df = DateFormat.getDateInstance();
        String preMonday = df.format(monday);
        return preMonday;
    }

    //获取当天时间 
    public String getNowTime(String dateformat) {
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat(dateformat);//可以方便地修改日期格式   
        String hehe = dateFormat.format(now);
        return hehe;
    }

    //获取当天时间 
    public static String getDateByformat(Date date, String dateformat) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(dateformat);//可以方便地修改日期格式   
        String hehe = dateFormat.format(date);
        return hehe;
    }

    /**
     * 获取当天时间
     * @param dateformat
     * @return
     */
    public static String getNowDateTime(String dateformat) {
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat(dateformat);//可以方便地修改日期格式   
        String hehe = dateFormat.format(now);
        return hehe;
    }

    // 获得当前日期与本周日相差的天数
    public static int getMondayPlus() {
        Calendar cd = Calendar.getInstance();
        // 获得今天是一周的第几天，星期日是第一天，星期二是第二天......
        int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK) - 1; //因为按中国礼拜一作为第一天所以这里减1
        if (dayOfWeek == 1) {
            return 0;
        } else {
            return 1 - dayOfWeek;
        }
    }

    //获得本周一的日期
    public String getMondayOFWeek() {
        weeks = 0;
        int mondayPlus = getMondayPlus();
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add(GregorianCalendar.DATE, mondayPlus);
        Date monday = currentDate.getTime();

        DateFormat df = DateFormat.getDateInstance();
        String preMonday = df.format(monday);
        return preMonday;
    }

    //获得相应周的周六的日期
    public String getSaturday() {
        int mondayPlus = getMondayPlus();
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add(GregorianCalendar.DATE, mondayPlus + 7 * weeks + 6);
        Date monday = currentDate.getTime();
        DateFormat df = DateFormat.getDateInstance();
        String preMonday = df.format(monday);
        return preMonday;
    }

    // 获得上周星期日的日期
    public String getPreviousWeekSunday() {
        weeks = 0;
        weeks--;
        int mondayPlus = getMondayPlus();
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add(GregorianCalendar.DATE, mondayPlus + weeks);
        Date monday = currentDate.getTime();
        DateFormat df = DateFormat.getDateInstance();
        String preMonday = df.format(monday);
        return preMonday;
    }

    // 获得上周星期一的日期
    public String getPreviousWeekday() {
        weeks--;
        int mondayPlus = getMondayPlus();
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add(GregorianCalendar.DATE, mondayPlus + 7 * weeks);
        Date monday = currentDate.getTime();
        DateFormat df = DateFormat.getDateInstance();
        String preMonday = df.format(monday);
        return preMonday;
    }

    // 获得下周星期一的日期
    public String getNextMonday() {
        weeks++;
        int mondayPlus = getMondayPlus();
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add(GregorianCalendar.DATE, mondayPlus + 7);
        Date monday = currentDate.getTime();
        DateFormat df = DateFormat.getDateInstance();
        String preMonday = df.format(monday);
        return preMonday;
    }

    // 获得下周星期日的日期
    public String getNextSunday() {

        int mondayPlus = getMondayPlus();
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add(GregorianCalendar.DATE, mondayPlus + 7 + 6);
        Date monday = currentDate.getTime();
        DateFormat df = DateFormat.getDateInstance();
        String preMonday = df.format(monday);
        return preMonday;
    }

    public int getMonthPlus() {
        Calendar cd = Calendar.getInstance();
        int monthOfNumber = cd.get(Calendar.DAY_OF_MONTH);
        cd.set(Calendar.DATE, 1);//把日期设置为当月第一天 
        cd.roll(Calendar.DATE, -1);//日期回滚一天，也就是最后一天 
        MaxDate = cd.get(Calendar.DATE);
        if (monthOfNumber == 1) {
            return -MaxDate;
        } else {
            return 1 - monthOfNumber;
        }
    }

    //获得上月最后一天的日期
    public String getPreviousMonthEnd() {
        String str = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Calendar lastDate = Calendar.getInstance();
        lastDate.add(Calendar.MONTH, -1);//减一个月
        lastDate.set(Calendar.DATE, 1);//把日期设置为当月第一天 
        lastDate.roll(Calendar.DATE, -1);//日期回滚一天，也就是本月最后一天 
        str = sdf.format(lastDate.getTime());
        return str;
    }

    //获得下个月第一天的日期
    public String getNextMonthFirst() {
        String str = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Calendar lastDate = Calendar.getInstance();
        lastDate.add(Calendar.MONTH, 1);//减一个月
        lastDate.set(Calendar.DATE, 1);//把日期设置为当月第一天 
        str = sdf.format(lastDate.getTime());
        return str;
    }

    //获得下个月最后一天的日期
    public String getNextMonthEnd() {
        String str = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Calendar lastDate = Calendar.getInstance();
        lastDate.add(Calendar.MONTH, 1);//加一个月
        lastDate.set(Calendar.DATE, 1);//把日期设置为当月第一天 
        lastDate.roll(Calendar.DATE, -1);//日期回滚一天，也就是本月最后一天 
        str = sdf.format(lastDate.getTime());
        return str;
    }

    //获得明年最后一天的日期
    public String getNextYearEnd() {
        String str = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Calendar lastDate = Calendar.getInstance();
        lastDate.add(Calendar.YEAR, 1);//加一个年
        lastDate.set(Calendar.DAY_OF_YEAR, 1);
        lastDate.roll(Calendar.DAY_OF_YEAR, -1);
        str = sdf.format(lastDate.getTime());
        return str;
    }

    //获得明年第一天的日期
    public String getNextYearFirst() {
        String str = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Calendar lastDate = Calendar.getInstance();
        lastDate.add(Calendar.YEAR, 1);//加一个年
        lastDate.set(Calendar.DAY_OF_YEAR, 1);
        str = sdf.format(lastDate.getTime());
        return str;

    }

    //获得本年有多少天
    public int getMaxYear() {
        Calendar cd = Calendar.getInstance();
        cd.set(Calendar.DAY_OF_YEAR, 1);//把日期设为当年第一天
        cd.roll(Calendar.DAY_OF_YEAR, -1);//把日期回滚一天。
        int MaxYear = cd.get(Calendar.DAY_OF_YEAR);
        return MaxYear;
    }

    private int getYearPlus() {
        Calendar cd = Calendar.getInstance();
        int yearOfNumber = cd.get(Calendar.DAY_OF_YEAR);//获得当天是一年中的第几天
        cd.set(Calendar.DAY_OF_YEAR, 1);//把日期设为当年第一天
        cd.roll(Calendar.DAY_OF_YEAR, -1);//把日期回滚一天。
        int MaxYear = cd.get(Calendar.DAY_OF_YEAR);
        if (yearOfNumber == 1) {
            return -MaxYear;
        } else {
            return 1 - yearOfNumber;
        }
    }

    //得到下一周的同一时间
    public static Date getNextWeek() {
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add(GregorianCalendar.DATE, 7);
        Date date = currentDate.getTime();
        return date;
    }

    //得到下一季度的同一时间
    public static Date getNextSeason() {
        Calendar lastDate = Calendar.getInstance();
        lastDate.add(Calendar.MONTH, 3);//加三个月
        return lastDate.getTime();
    }

    //得到下个月的同一时间
    public static Date getNextMonth() {
        Calendar lastDate = Calendar.getInstance();
        lastDate.add(Calendar.MONTH, 1);//加一个月
        return lastDate.getTime();
    }

    //得到下个月的同一时间
    public static Date getLastMonth() {
        Calendar lastDate = Calendar.getInstance();
        lastDate.add(Calendar.MONTH, -1);//减一个月
        lastDate.add(Calendar.DAY_OF_MONTH, 1);//加一天
        return lastDate.getTime();
    }

    public static boolean isBenyue(Date date) {
        Calendar cBefore = Calendar.getInstance();
        cBefore.add(Calendar.MONTH, -1);
        int endDate = cBefore.getActualMaximum(Calendar.DAY_OF_MONTH);
        cBefore.set(Calendar.DAY_OF_MONTH, endDate);

        Calendar cNext = Calendar.getInstance();
        cNext.add(Calendar.MONTH, 1);
        cNext.set(Calendar.DAY_OF_MONTH, 1);

        Calendar cNow = Calendar.getInstance();
        if (null == date) {
            return true;
        }
        cNow.setTime(date);
        cNow.set(Calendar.HOUR_OF_DAY, 0);
        cNow.set(Calendar.MINUTE, 0);
        cNow.set(Calendar.SECOND, 0);
        return cNow.compareTo(cNext) < 0 && cNow.compareTo(cBefore) > 0;

    }

    /**
     * 将日期+frequency天
     * @param date YYYY-mm-DD 格式的字符串
     * @param frequency 天数
     * @return
     */
    public static String getNextDate(String date, int frequency) {
        SimpleDateFormat ddf = new SimpleDateFormat("yyyy-MM-dd");
        Date d = null;
        try {
            d = ddf.parse(date);
        } catch (Exception e) {
        }
        Calendar c = Calendar.getInstance();
        c.setTime(d);
        c.add(Calendar.DAY_OF_MONTH,frequency);
        return ddf.format(c.getTime());
    }

    /**
     * 根据某个日期和频次得到下次执行日期
     * 上次创建日期为NULL时，返回明天日期
     * @param lastTime
     * @param frequency
     * @return
     */
    public static Date getNextTime(Date lastTime, Integer frequency) {
        Calendar lastCal = Calendar.getInstance();
        Calendar c = Calendar.getInstance();
        int maxDay = c.getActualMaximum(Calendar.DAY_OF_MONTH);
        int eachDay = maxDay / frequency;
        if (lastTime != null) {//如果有最后执行时间，设置此时间为起点,并向后延迟eachDay多天
            lastCal.setTime(lastTime);
            lastCal.add(Calendar.DAY_OF_MONTH, eachDay);
        } else {//返回第二天
            lastCal.add(Calendar.DAY_OF_MONTH, 1);
        }
        if (lastCal.get(Calendar.MONTH) != c.get(Calendar.MONTH)) {
            lastCal.set(Calendar.DATE, 1);
        }
        return lastCal.getTime();
    }

    /**
     * 根据某个日期和频次得到下次执行日期
     * 上次创建日期为NULL时，返回明天日期
     * @param lastTime
     * @param frequency
     * @return
     */
    public static Date getNextTime1(Date lastTime, Integer frequency) {
        Calendar lastCal = Calendar.getInstance();
        Calendar a = Calendar.getInstance();
        a.setTime(lastTime);
        a.set(Calendar.DATE, 1); //把日期设置为当月第一天
        a.roll(Calendar.DATE, -1); //日期回滚一天，也就是最后一天
        int maxDay = a.get(Calendar.DATE);
        int eachDay = maxDay / frequency;
        if (lastTime != null) {//如果有最后执行时间，设置此时间为起点,并向后延迟eachDay多天
            lastCal.setTime(lastTime);
            int cur = lastCal.get(Calendar.DAY_OF_MONTH);
            if (cur >= 15) {
                lastCal.set(Calendar.DAY_OF_MONTH, maxDay);
            } else {
                lastCal.add(Calendar.DAY_OF_MONTH, eachDay);
            }
        } else {//返回第二天
            lastCal.add(Calendar.DAY_OF_MONTH, 1);
        }
        return lastCal.getTime();
    }

    /**
     * 得到设备下次创建任务日期
     * 上次创建日期为NULL时，返回明天日期
     * @param lastTime
     * @param month
     * @return
     */
    public static Date getNextSBTime(Date lastTime, Integer month) {
        Calendar lastCal = Calendar.getInstance();
        if (lastTime != null) {//如果有最后执行时间，设置此时间为起点,并向后延迟eachDay多天
            lastCal.setTime(lastTime);
            lastCal.add(Calendar.MONTH, month);
        } else {//返回第二天
            lastCal.add(Calendar.DAY_OF_MONTH, 1);
        }
        return lastCal.getTime();
    }

    public static String lastMonFirstDay() {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.add(Calendar.DAY_OF_MONTH, -1);
        String months = "";
        if (month > 1) {
            month--;
        } else {
            year--;
            month = 12;
        }
        if (!(String.valueOf(month).length() > 1)) {
            months = "0" + month;
        } else {
            months = String.valueOf(month);
        }
        String firstDay = "" + year + "-" + months + "-01";
        String[] lastMonth = new String[2];
        lastMonth[0] = firstDay;
        return firstDay;
    }

    public static String lastMonLastDay() {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.add(Calendar.DAY_OF_MONTH, -1);
        int day = cal.get(Calendar.DAY_OF_MONTH);
        String months = "";
        String days = "";
        if (month > 1) {
            month--;
        } else {
            year--;
            month = 12;
        }
        if (!(String.valueOf(month).length() > 1)) {
            months = "0" + month;
        } else {
            months = String.valueOf(month);
        }
        if (!(String.valueOf(day).length() > 1)) {
            days = "0" + day;
        } else {
            days = String.valueOf(day);
        }
        String lastDay = "" + year + "-" + months + "-" + days;
        String[] lastMonth = new String[2];
        lastMonth[1] = lastDay;
        return lastDay;
    }

    /**
     * 获得当前年份
     * @return
     */
    public static int getCurYear() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new java.util.Date());
        int year = calendar.get(Calendar.YEAR); //获得当前年份
        return year;
    }

    /**
     * 获得当前季度（数字）
     * @return
     */
    public static int getCurQuarter() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new java.util.Date());
        int month = calendar.get(Calendar.MONTH) + 1; //获得当前月份
        int quarter = 0;
        if (month >= 1 && month <= 3) {
            quarter = 1;
        }
        if (month >= 4 && month <= 6) {
            quarter = 2;
        }
        if (month >= 7 && month <= 9) {
            quarter = 3;
        }
        if (month >= 10 && month <= 12) {
            quarter = 4;
        }
        return quarter;
    }
    

}
